#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <errno.h>
#include <vector>
#include <sys/epoll.h>


void SetNonBlock(int fd)
{
    int flags = fcntl(fd,F_GETFL,0);//显示传0表示无额外参数
    fcntl(fd,F_SETFL,flags | O_NONBLOCK);//设置非阻塞
}

int BulidConnect(int listensock)
{
    int sockfd = accept(listensock,nullptr,nullptr);//不关心客户端情况
    return sockfd;
}

bool ReadMessage(int sockfd)
{
    //非阻塞模式下,循环读取,以读取完所有内容
    std::string str;
    while(true)
    {
        char buffer[1024] = {0};
        int n = recv(sockfd,buffer,sizeof(buffer) - 1,0); 
        if(n <= sizeof(buffer) - 1 && n > 0)
        {
            //不确定数据是否读完,继续读
            buffer[n] = 0;
            str += buffer;
            continue;
        }
        else if(n == 0)
        {
            //对端连接关闭,同时接收缓冲区中也没有数据
            if(str.size())
            {
                std::cout << str << std::endl;
                std::string echo_str = "echo: " + str;
                send(sockfd,echo_str.c_str(),echo_str.size(),0);
            }
            return false;
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                //非阻塞模式下,数据读取完毕
                break;
            }
            else if(errno == EINTR)
                continue;
            else
                break;
        }
    }
    if(str.size())
    {
        std::cout << str << std::endl;
        std::string echo_str = "echo: " + str;
        send(sockfd,echo_str.c_str(),echo_str.size(),0);
    }
    return true;
}

int main()
{
    int listensock = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;//服务器显示绑定地址:任意IP绑定
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8080);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    int opt = 1;
    setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
    if(bind(listensock,(struct sockaddr*)&addr,sizeof(addr)) != 0)
        std::cout << "bind error" << std::endl;
    if(listen(listensock,64) != 0)
        std::cout << "listen error" << std::endl;
    SetNonBlock(listensock);   
    
    //存储epoll_wait输出型参数
    struct epoll_event buffer[1024];
    
    int epfd = epoll_create(64);//这个参数大于0即可,已经被忽略了

    //设置listensock
    struct epoll_event listen_epoll;
    listen_epoll.events = EPOLLIN,listen_epoll.data.fd = listensock;//使用默认的LT模式
    if(epoll_ctl(epfd,EPOLL_CTL_ADD,listensock,&listen_epoll) != 0)
        std::cout << "epoll_ctl error" << std::endl;
    while(true)
    {
        int n = epoll_wait(epfd,buffer,sizeof(buffer) / sizeof(buffer[0]),-1);//阻塞模式
        if(n > 0)
        {
            //n是个数
            for(int i = 0;i < n;i++)
            {
                int fd = buffer[i].data.fd;
                int events = buffer[i].events;
                if(fd == listensock && (events & EPOLLIN))
                {
                    int sockfd = BulidConnect(fd);
                    SetNonBlock(sockfd);
                    struct epoll_event sock_epoll;
                    sock_epoll.events = EPOLLIN,sock_epoll.data.fd = sockfd;//使用默认的LT模式
                    if(epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&sock_epoll) != 0)
                        std::cout << "epoll_ctl add error" << std::endl;
                }
                else if(events & EPOLLIN)
                {
                    if(!ReadMessage(fd))
                    {
                        std::cout << "对端断开连接,socket: " << fd << "关闭" << std::endl;
                        if(epoll_ctl(epfd,EPOLL_CTL_DEL,fd,nullptr) != 0)
                            std::cout << "epoll_ctl del error" << std::endl;
                        close(fd);//注意此处的顺序,先epoll_ctl删除,之后再close:其实直接close即可,会自动从epoll中移除,但是手动epoll_ctl删除,逻辑更明确
                    }
                }
            }
        }
        else if(n == 0)
            std::cout << "epoll timeout" << std::endl;
        else
            std::cout << "epoll error" << std::endl;
    }
    return 0;
}